<template>
  <view class="village-canvas-container">
    <!-- Canvas画布 -->
    <canvas 
      :canvas-id="canvasId"
      :id="canvasId"
      class="village-canvas"
      :style="canvasStyle"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      @tap="handleTap"
      @longpress="handleLongPress"
    ></canvas>
    
    <!-- 顶部资源栏 -->
    <view class="resource-bar">
      <view class="resource-item" v-for="(resource, key) in resources" :key="key">
        <text class="resource-icon">{{ resource.icon }}</text>
        <text class="resource-value">{{ Math.floor(resource.amount) }}</text>
        <text class="resource-change" :class="{ positive: resource.change > 0, negative: resource.change < 0 }">
          {{ resource.change > 0 ? '+' : '' }}{{ resource.change }}/h
        </text>
      </view>
    </view>
    
    <!-- 建筑详情弹窗 -->
    <view v-if="selectedBuilding" class="building-detail-popup" @click.stop="">
      <view class="popup-header">
        <text class="popup-title">{{ selectedBuilding.name }}</text>
        <button class="close-btn" @click="closePopup">×</button>
      </view>
      <view class="popup-content">
        <text class="building-level">等级 {{ selectedBuilding.level }}</text>
        <text class="building-desc">{{ selectedBuilding.description }}</text>
        <button class="upgrade-btn" @click="upgradeBuilding" :disabled="!canUpgrade">
          升级 ({{ upgradeCost }} 木材)
        </button>
      </view>
    </view>
    
    <!-- 性能指标（调试模式） -->
    <view v-if="debugMode" class="debug-info">
      <text class="debug-text">FPS: {{ fps }}</text>
      <text class="debug-text">Buildings: {{ buildingCount }}</text>
      <text class="debug-text">Villagers: {{ villagerCount }}</text>
    </view>
  </view>
</template>

<script>
import VillageRenderer from '@/utils/village-renderer/VillageRenderer.js'
import { getGlobalRenderLoop } from '@/utils/pet-renderer/RenderLoop.js'

export default {
  name: 'VillageCanvas',
  props: {
    gameData: {
      type: Object,
      required: true
    },
    buildings: {
      type: Array,
      default: () => []
    },
    villagers: {
      type: Array,
      default: () => []
    },
    events: {
      type: Array,
      default: () => []
    },
    weather: {
      type: String,
      default: 'sunny'
    },
    timeOfDay: {
      type: Number,
      default: 12
    },
    debugMode: {
      type: Boolean,
      default: false
    }
  },
  
  data() {
    return {
      canvasId: 'villageCanvas_' + Date.now(),
      ctx: null,
      renderer: null,
      renderLoop: null,
      isInitialized: false,
      pixelRatio: 1,
      
      // 交互状态
      selectedBuilding: null,
      touchStartPos: null,
      isDragging: false,
      draggingBuilding: null,
      
      // 性能指标
      fps: 60,
      
      // 资源数据
      resources: {}
    }
  },
  
  computed: {
    canvasStyle() {
      return {
        width: '750rpx',
        height: '1000rpx'
      }
    },
    
    buildingCount() {
      return this.buildings.length
    },
    
    villagerCount() {
      return this.villagers.length
    },
    
    canUpgrade() {
      if (!this.selectedBuilding) return false
      return this.gameData.resources.wood.amount >= this.upgradeCost
    },
    
    upgradeCost() {
      if (!this.selectedBuilding) return 0
      return Math.floor(this.selectedBuilding.baseCost * Math.pow(1.4, this.selectedBuilding.level))
    }
  },
  
  watch: {
    gameData: {
      handler(newData) {
        this.updateResources(newData.resources)
      },
      deep: true,
      immediate: true
    }
  },
  
  mounted() {
    this.$nextTick(() => {
      this.initCanvas()
    })
  },
  
  beforeDestroy() {
    this.cleanup()
  },
  
  methods: {
    /**
     * 初始化Canvas
     */
    initCanvas() {
      try {
        // 获取系统信息
        const systemInfo = uni.getSystemInfoSync()
        this.pixelRatio = systemInfo.pixelRatio || 1
        
        // 创建Canvas上下文
        this.ctx = uni.createCanvasContext(this.canvasId, this)
        
        if (!this.ctx) {
          console.error('Failed to create canvas context')
          this.$emit('canvas-error', { message: 'Canvas not supported' })
          return
        }
        
        // 计算实际尺寸
        const actualWidth = 750 * systemInfo.windowWidth / 750
        const actualHeight = 1000 * systemInfo.windowWidth / 750
        
        // 创建渲染器
        this.renderer = new VillageRenderer(this.ctx, {
          width: actualWidth,
          height: actualHeight,
          pixelRatio: this.pixelRatio,
          debugMode: this.debugMode
        })
        
        // 获取全局渲染循环
        this.renderLoop = getGlobalRenderLoop({
          targetFPS: 60,
          autoAdjustFPS: true,
          minFPS: 30
        })
        
        // 添加渲染器到渲染循环
        this.renderLoop.addRenderer({
          render: (timestamp, deltaTime) => {
            this.renderFrame(timestamp, deltaTime)
          }
        })
        
        // 启动渲染循环
        if (!this.renderLoop.isRunning) {
          this.renderLoop.start()
        }
        
        this.isInitialized = true
        this.$emit('canvas-ready')
        
        console.log('VillageCanvas initialized successfully')
        
      } catch (error) {
        console.error('Failed to initialize canvas:', error)
        this.$emit('canvas-error', { message: error.message })
      }
    },
    
    /**
     * 渲染一帧
     */
    renderFrame(timestamp, deltaTime) {
      if (!this.renderer || !this.isInitialized) return
      
      const sceneData = {
        buildings: this.buildings,
        villagers: this.villagers,
        events: this.events,
        weather: this.weather,
        timeOfDay: this.timeOfDay
      }
      
      this.renderer.render(sceneData, timestamp)
      
      // 更新FPS
      if (this.debugMode) {
        this.fps = Math.round(1000 / deltaTime)
      }
    },
    
    /**
     * 更新资源显示
     */
    updateResources(resources) {
      this.resources = {
        wood: {
          icon: '🪵',
          amount: resources.wood?.amount || 0,
          change: resources.wood?.change || 0
        },
        food: {
          icon: '🌾',
          amount: resources.food?.amount || 0,
          change: resources.food?.change || 0
        },
        population: {
          icon: '👥',
          amount: resources.population?.amount || 0,
          change: resources.population?.change || 0
        }
      }
    },
    
    /**
     * 处理触摸开始
     */
    handleTouchStart(e) {
      if (!this.renderer) return
      
      const sceneData = {
        buildings: this.buildings,
        villagers: this.villagers
      }
      
      const result = this.renderer.handleTouchStart(e, sceneData)
      
      if (result) {
        if (result.type === 'building-touch-start') {
          // 建筑被触摸
          this.draggingBuilding = result.target
          this.renderer.buildingManager.startDrag(result.target)
          console.log('Building touched:', result.target)
        } else if (result.type === 'villager-touch-start') {
          // 村民被触摸
          console.log('Villager touched:', result.target)
        }
      }
    },
    
    /**
     * 处理触摸移动
     */
    handleTouchMove(e) {
      if (!this.renderer) return
      
      const result = this.renderer.handleTouchMove(e)
      
      if (result) {
        if (result.type === 'camera-drag') {
          // 相机拖拽已在renderer中处理
          this.isDragging = true
        } else if (result.type === 'building-drag') {
          // 建筑拖拽
          this.isDragging = true
          this.renderer.buildingManager.updateDragPosition(result.position)
          console.log('Building dragging:', result.target, result.position)
        }
      }
    },
    
    /**
     * 处理触摸结束
     */
    handleTouchEnd(e) {
      if (!this.renderer) return
      
      const result = this.renderer.handleTouchEnd(e)
      
      if (result) {
        if (result.type === 'building-tap') {
          // 点击建筑
          this.selectedBuilding = result.target
          console.log('Building tapped:', result.target)
        } else if (result.type === 'building-double-tap') {
          // 双击建筑 - 快速升级
          this.$emit('upgrade-building', result.target.id)
        } else if (result.type === 'villager-tap') {
          // 点击村民
          this.showVillagerInfo(result.target)
        } else if (result.type === 'empty-tap') {
          // 点击空地 - 检查是否点击了事件
          const worldPos = this.renderer.screenToWorld(e.detail.x, e.detail.y)
          const hitEvent = this.renderer.hitTestEvent(worldPos.x, worldPos.y)
          
          if (hitEvent) {
            this.handleEventClick(hitEvent)
          } else {
            this.selectedBuilding = null
          }
        } else if (result.type === 'building-drop') {
          // 建筑拖拽结束
          const isAvailable = this.renderer.buildingManager.isPositionAvailable(
            result.position,
            this.buildings,
            result.target
          )
          
          if (isAvailable) {
            this.$emit('move-building', {
              building: result.target,
              position: result.gridPosition
            })
          } else {
            // 位置不可用，显示提示
            uni.showToast({
              title: '该位置已被占用',
              icon: 'none'
            })
          }
        }
      }
      
      // 结束拖拽
      this.renderer.buildingManager.endDrag()
      this.draggingBuilding = null
      this.isDragging = false
    },
    
    /**
     * 处理点击
     */
    handleTap(e) {
      // 由handleTouchEnd处理
    },
    
    /**
     * 处理长按
     */
    handleLongPress(e) {
      if (!this.renderer) return
      
      const sceneData = {
        buildings: this.buildings,
        villagers: this.villagers
      }
      
      const result = this.renderer.handleLongPress(e, sceneData)
      
      if (result) {
        if (result.type === 'building-long-press') {
          // 长按建筑 - 显示详细菜单
          this.showBuildingMenu(result.target)
        } else if (result.type === 'villager-long-press') {
          // 长按村民 - 显示详细信息
          this.showVillagerMenu(result.target)
        } else if (result.type === 'empty-long-press') {
          // 长按空地 - 显示建造菜单
          this.$emit('show-build-menu', result.gridPosition)
        }
      }
    },
    
    /**
     * 显示村民信息
     */
    showVillagerInfo(villager) {
      uni.showModal({
        title: villager.name || '村民',
        content: `职业: ${this.getJobName(villager.job)}\n心情: ${villager.mood || 50}\n能量: ${villager.energy || 50}`,
        showCancel: false
      })
    },
    
    /**
     * 显示建筑菜单
     */
    showBuildingMenu(building) {
      uni.showActionSheet({
        itemList: ['升级', '移动', '拆除'],
        success: (res) => {
          if (res.tapIndex === 0) {
            this.$emit('upgrade-building', building.id)
          } else if (res.tapIndex === 1) {
            // 进入移动模式
            console.log('Enter move mode for building:', building)
          } else if (res.tapIndex === 2) {
            this.$emit('demolish-building', building.id)
          }
        }
      })
    },
    
    /**
     * 显示村民菜单
     */
    showVillagerMenu(villager) {
      uni.showActionSheet({
        itemList: ['分配工作', '查看详情', '休息'],
        success: (res) => {
          if (res.tapIndex === 0) {
            this.$emit('assign-job', villager.id)
          } else if (res.tapIndex === 1) {
            this.showVillagerInfo(villager)
          } else if (res.tapIndex === 2) {
            this.$emit('villager-rest', villager.id)
          }
        }
      })
    },
    
    /**
     * 获取职业名称
     */
    getJobName(job) {
      const names = {
        farmer: '农民',
        worker: '工人',
        merchant: '商人',
        scholar: '学者',
        idle: '闲置'
      }
      return names[job] || '未知'
    },
    
    /**
     * 处理事件点击
     */
    handleEventClick(event) {
      console.log('Event clicked:', event)
      
      // 显示事件详情
      const eventNames = {
        resource_found: '发现资源',
        visitor_arrived: '访客到来',
        disaster: '灾难警告',
        celebration: '庆祝活动',
        quest_available: '任务可用',
        achievement: '成就解锁'
      }
      
      const title = eventNames[event.type] || '事件'
      const content = event.data.description || event.data.title || '点击查看详情'
      
      uni.showModal({
        title: title,
        content: content,
        confirmText: '查看',
        cancelText: '关闭',
        success: (res) => {
          if (res.confirm) {
            this.$emit('event-click', event)
          }
        }
      })
    },
    
    /**
     * 升级建筑
     */
    upgradeBuilding() {
      if (!this.selectedBuilding || !this.canUpgrade) return
      
      this.$emit('upgrade-building', this.selectedBuilding.id)
      this.closePopup()
    },
    
    /**
     * 关闭弹窗
     */
    closePopup() {
      this.selectedBuilding = null
    },
    
    /**
     * 清理资源
     */
    cleanup() {
      if (this.renderLoop && this.renderer) {
        this.renderLoop.removeRenderer(this.renderer)
      }
      
      if (this.renderer) {
        this.renderer.destroy()
        this.renderer = null
      }
      
      this.ctx = null
      this.isInitialized = false
      
      console.log('VillageCanvas cleaned up')
    }
  }
}
</script>

<style scoped>
.village-canvas-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.village-canvas {
  width: 100%;
  height: 100%;
  display: block;
}

/* 资源栏 */
.resource-bar {
  position: absolute;
  top: 20rpx;
  left: 20rpx;
  right: 20rpx;
  display: flex;
  justify-content: space-around;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20rpx;
  padding: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.resource-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5rpx;
}

.resource-icon {
  font-size: 40rpx;
}

.resource-value {
  font-size: 28rpx;
  font-weight: bold;
  color: #2D6A4F;
}

.resource-change {
  font-size: 20rpx;
  color: #666;
}

.resource-change.positive {
  color: #52B788;
}

.resource-change.negative {
  color: #E63946;
}

/* 建筑详情弹窗 */
.building-detail-popup {
  position: absolute;
  bottom: 100rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 600rpx;
  background: white;
  border-radius: 20rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.2);
  z-index: 20;
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    transform: translateX(-50%) translateY(100%);
    opacity: 0;
  }
  to {
    transform: translateX(-50%) translateY(0);
    opacity: 1;
  }
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #2D6A4F;
}

.close-btn {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background: #f5f5f5;
  border: none;
  font-size: 40rpx;
  line-height: 60rpx;
  text-align: center;
  color: #666;
}

.popup-content {
  padding: 30rpx;
}

.building-level {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 15rpx;
}

.building-desc {
  display: block;
  font-size: 26rpx;
  color: #333;
  line-height: 1.5;
  margin-bottom: 30rpx;
}

.upgrade-btn {
  width: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 15rpx;
  padding: 25rpx;
  font-size: 28rpx;
  font-weight: bold;
}

.upgrade-btn:disabled {
  background: #ccc;
  color: #999;
}

/* 调试信息 */
.debug-info {
  position: absolute;
  top: 150rpx;
  left: 20rpx;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 20rpx;
  border-radius: 10rpx;
  font-size: 22rpx;
  z-index: 30;
}

.debug-text {
  display: block;
  margin-bottom: 10rpx;
}
</style>
